<template>
  <div class="editor" ref="divRef">
    <div class="aie-container">
      <div class="aie-container-header" />
      <div class="aie-container-main" />
      <div class="aie-container-footer" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { AiEditor } from "aieditor"
import "aieditor/dist/style.css"
import { onMounted, onUnmounted, ref, watch } from "vue"
import { serverDefaultCfg } from '@/common/http/config';

import { ElMessage } from "element-plus"

const $emit = defineEmits(["change"])

const $props = defineProps(["value"])

const divRef = ref()

let aiEditor = null

onMounted(() => {
  init()
})

const init = () => {
  aiEditor = new AiEditor({
    element: divRef.value,
    placeholder: "点击输入内容...",
    // 是否可以拖拽编辑框
    draggable: false,
    // 排除部分工具
    toolbarExcludeKeys: [
      "brush",
      "eraser",
      "link",
      "code",
      "todo",
      "emoji",
      "video",
      "ai",
      "video",
      "printer",
      "source-code",
      "attachment",
      "quote",
      "container",
      "code-block",
      "table"
    ],
    image: {
      // 图片上传接口
      uploadUrl: serverDefaultCfg.ossURL,
      uploadFormName: "file",

      uploader: (file, uploadUrl, headers, formName) => {
        const formData = new FormData();
        formData.append("file", file);
        return new Promise((resolve, reject) => {
          fetch(uploadUrl, {
            method: "post",
            body: formData,
          }).then((resp) => resp.json())
            .then(json => {
              resolve(json);
            }).catch((error) => {
              reject(error);
            })
        });

      },
      uploaderEvent: {
        onSuccess: (_file, response) => {
          console.log("upload success", response);

          if (response.success) {
            // 后端接口返回数据不符合规定格式时，自定义返回数据

            return {
              errorCode: 0,
              data: {
                // 上传成功接口返回的图片地址
                src: response.data.downloadUri,
                width: "auto",
                height: "200px",
                class: "image_class",
                loading: true
              }
            }
          }
        },
        onFailed: () => {
          ElMessage.error("图片上传失败")
        },
        onError: () => {
          ElMessage.error("图片上传错误")
        }
      },
      bubbleMenuItems: ["AlignLeft", "AlignCenter", "AlignRight", "delete",]
    },
    onChange: (aiEditor) => {
      // 监听到编辑器内容发生变化了，控制台打印编辑器的 html 内容...
      console.log(aiEditor.getHtml())

      // 向父组件传值
      if (aiEditor.getHtml() == "<p></p>") {
        $emit("change", "")
      } else {
        $emit("change", aiEditor.getHtml())
      }
    }
  })

  // 初始值回显
  if ($props.value) {
    aiEditor.focus().insert($props.value)
  }
}

watch(
  () => $props.value,
  (v) => {
    // console.log(v)
    if (!v) {
      aiEditor?.clear()
      $emit("change", undefined)
    }
  },
  {
    immediate: true
  }
)

onUnmounted(() => {
  aiEditor && aiEditor.destroy()
})
</script>

<style lang="scss" scoped>
.editor {
  width: 100%;
}

.aie-container-main {
  height: 400px;
  overflow-y: auto;
}

.aie-container-footer {
  display: none;
}
</style>
